package platformlog_logic

import (
	"context"
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/sqlx"

	"yunzhan/api-server/internal/svc"
	"yunzhan/api-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeleteClusterInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewDeleteClusterInfoLogic 删除集群
func NewDeleteClusterInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteClusterInfoLogic {
	return &DeleteClusterInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DeleteClusterInfoLogic) DeleteClusterInfo(req *types.DeleteClusterInfoRequest) (resp *types.ClusterInfoResponse, err error) {
	var tableName string
	if l.svcCtx.Config.UseMysql {
		tableName = l.svcCtx.Config.Mysql.Tables.ClusterInfo
	} else {
		tableName = l.svcCtx.Config.SQLite.Tables.ClusterInfo
	}

	deleteSQL := fmt.Sprintf(`DELETE FROM %s WHERE cluster_id = ?`, tableName)
	checkExistSQL := fmt.Sprintf(`SELECT EXISTS(SELECT 1 FROM %s WHERE cluster_id = ?)`, tableName)

	// 使用sqlx的Transact方法开始事务
	err = l.svcCtx.Conn.Transact(func(session sqlx.Session) error {
		// 先检查cluster_id是否存在
		var exists bool
		err := session.QueryRow(&exists, checkExistSQL, req.ClusterID)
		if err != nil {
			return fmt.Errorf("检查cluster_id存在性失败: %w", err)
		}
		if !exists {
			return errors.New("cluster_id不存在: " + req.ClusterID)
		}

		// 删除指定的cluster_info记录
		_, err = session.Exec(deleteSQL, req.ClusterID)
		if err != nil {
			return fmt.Errorf("删除cluster_info失败: %w", err)
		}
		return nil
	})

	if err != nil {
		return &types.ClusterInfoResponse{
			Code:    500,
			Message: fmt.Sprintf("集群删除失败: %v", err),
			Data:    []types.ClusterInfo{},
		}, err
	}

	return &types.ClusterInfoResponse{
		Code:    200,
		Message: "集群删除成功",
		Data:    []types.ClusterInfo{},
	}, nil
}
